package com.sys.role.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sys.role.entity.SysRole;
import com.sys.role.mapper.SysRoleMapper;
import com.sys.role.service.SysRoleService;
import com.sys.role.view.SysRoleView;
import com.sys.rolemenu.entity.SysRoleMenu;
import com.sys.rolemenu.service.SysRoleMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author djianfeng
 * @since 2018-07-24
 */
@Transactional
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    SysRoleMapper roleMapper;
    @Autowired
    SysRoleMenuService roleMenuService;

    @Override
    public List<SysRoleView> getSysRoleViews(Page<SysRoleView> page, SysRoleView view) {
        page.setRecords(roleMapper.getSysRoleViews(page,view));
        return page.getRecords();
    }

    @Override
    public boolean save(SysRoleView view) {
        SysRole role = new SysRole();
        BeanUtils.copyProperties(view, role);
        this.insertOrUpdate(role);
        Map map = new HashMap();
        map.put("role_id", role.getId());
        this.roleMenuService.deleteByMap(map);
        Long[] menuIds = view.getMenuIds();
        if (menuIds != null && menuIds.length > 0) {
            for (int i = 0; i < menuIds.length; i++) {
                SysRoleMenu roleMenu = new SysRoleMenu();
                roleMenu.setRoleId(role.getId());
                roleMenu.setMenuId(menuIds[i]);
                this.roleMenuService.insert(roleMenu);
            }
        }
        return false;
    }
}
